package com.qiyou.controller;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.logging.Logger;


/**
 * Created by dell on 2018/9/6.
 */
@Controller
@RequestMapping("/file")
public class FileController {
    private static Logger logger = Logger.getLogger(String.valueOf(FileController.class));
    private boolean saveFile(MultipartFile file, String path) throws IOException {

        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                File filepath = new File(path);
                if (!filepath.exists())
                // 文件保存路径
                    filepath.mkdirs();
                // 文件保存路径
                String savePath = path ;
                // 转存文件
                file.transferTo(new File(savePath));
                return true;
            } catch (IOException e) {
                throw new RuntimeException("上传文件失败");
            }
        }
        return false;
    }
    /**
     * 上传图片
     */
    @RequestMapping("/imageUpload")
    @ResponseBody
    public String imageUpload(@RequestParam("files") MultipartFile file, HttpServletRequest request, HttpServletResponse response)throws Exception {
      String filename = null;

        String path =  "\\resources\\upload\\"+new Date().getTime()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
        String dir = "";

        JSONObject result = new JSONObject();

              if(saveFile(file,request.getSession().getServletContext().getRealPath("/")+ path)){

                dir =path;
              }


        return dir;

    }




}
